package com.clss.commandhelper.base;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.clss.commandhelper.CommandHelperApplication;
import com.clss.commandhelper.R;
import com.clss.commandhelper.function.login.LoginActivity;
import com.clss.commandhelper.tools.ActivityTracker;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.Lg;
import com.clss.commandhelper.tools.SpHelper;
import com.clss.commandhelper.tools.UploadHelper;
import com.clss.commandhelper.tools.Utils;
import com.clss.commandhelper.tools.VersionUpdataHelper;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.clss.commandhelper.tools.eventbus.EventBusMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;

import butterknife.ButterKnife;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * Activity类的父类
 *
 * @author Liuv
 * @date 2017/4/12
 */

public abstract class BaseActivity extends AppCompatActivity implements BaseView {
    private static final String TAG = "BaseActivity";
    protected Toast mToast;
    protected ProgressDialog mProgressDialog;
    public CommandHelperApplication commandHelperApplication;
    public Animation fade_in;
    public Animation fade_out;
    protected File mCamareFile;
    protected File mVideoCameraFile;
    protected AMapLocationClient locationClient;
    protected AMapLocationClientOption locationOption;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActivityTracker.onCreate(this);
        commandHelperApplication = (CommandHelperApplication)getApplication();
        fade_in = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        fade_out = AnimationUtils.loadAnimation(this, R.anim.fade_out);
        setContentView(setViewId());
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initData(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
//        Lg.i(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
//        MobclickAgent.onPause(this);
//        Lg.i(TAG, "onPause");
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
//        destroyLocation();
        dismissLoadingDialog();
        super.onDestroy();
        ActivityTracker.onDestory(this);
//        Lg.i(TAG, "onDestroy");
    }

    @Override
    public void finish() {
        super.finish();
    }

    protected abstract int setViewId();
    protected abstract void initView();
    protected abstract void initData(@Nullable Bundle savedInstanceState);

    @Subscribe
    public void onEventMainThread(EventBusMessage eventBusMessage) {
        if (eventBusMessage.getCode() == Constant.SESSION_TIMEOUT){
            showShortToast("登录状态失效，请重新登录");
            SpHelper.getInstance().clearAll();
            Utils.startActivity(this, LoginActivity.class);
            ActivityTracker.finishAll();
        }
    }

    @Override
    public void showLoadingDialog() {
        showLoadingDialog(null, getString(R.string.please_wait));
    }

    @Override
    public void showLoadingDialog(String msg) {
        showLoadingDialog(null, msg);
    }

    public void showLoadingDialog(String title, String message){
        if (mProgressDialog == null){
            mProgressDialog = new ProgressDialog(this, 5);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }

        if (title == null) {
            title = "";
        }
        if (message == null) {
            message = "";
        }
        mProgressDialog.setTitle(title);
        mProgressDialog.setMessage(message);
        mProgressDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
        }
    }

    @Override
    public Context getActContext() {
        return this;
    }


    @Override
    public void showLongToast(int messageId) {
        showLongToast(getString(messageId));
    }

    @Override
    public void showLongToast(final String message) {
        if (TextUtils.isEmpty(message)){
            return;
        }
        if ((getString(R.string.token_is_useless)).equals(message)){
            return;
        }
        runOnUiThread(() -> Toast.makeText(getActContext(), message, Toast.LENGTH_LONG).show());
    }

    @Override
    public void showShortToast(int messageId) {
        showShortToast(getString(messageId));
    }

    @Override
    public void showShortToast(final String message) {
        if (TextUtils.isEmpty(message)){
            return;
        }
        if ((getString(R.string.token_is_useless)).equals(message)){
            return;
        }
        runOnUiThread(() -> Toast.makeText(getActContext(), message, Toast.LENGTH_SHORT).show());
    }

    protected void chooseLocImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, Constant.REQUEST_CODE_IMAGE);
    }

    protected void chooseLocVideo(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        startActivityForResult(intent, Constant.REQUEST_CODE_VIDEO);
    }

    public void getImageFromCaramer(){
        mCamareFile = UploadHelper.getCameraSaveFile(this, System.currentTimeMillis());
        UploadHelper.selectImageFromCamera(this, Constant.REQUEST_CODE_CAMARE, mCamareFile);
    }
    public void getVideoFromCamera(){
        mVideoCameraFile = UploadHelper.getCameraSaveVideoFile(this, System.currentTimeMillis());
        UploadHelper.selectVideoFromCamera(this, Constant.REQUEST_CODE_VIDEO, mVideoCameraFile);
    }

    private Toast checkNullOrNew(){
        if (mToast == null){
            mToast = new Toast(this);
        }
        return mToast;
    }

    @Override
    public void requestFailure(Throwable t) {
        if (t.toString().contains(Constant.TIMEOUT_EXCEPTION)){
            showShortToast(getString(R.string.servicer_no_response));
        }
    }

    public void showInteractionDialog(String msg, DialogInterface.OnClickListener okListener){
        showInteractionDialog(msg, true, "确认", "取消", okListener, (dialog, which) -> dialog.dismiss());
    }

    public void showInteractionDialog(String msg, boolean cancelable, String ok, String no,
                                      DialogInterface.OnClickListener okListener,
                                      DialogInterface.OnClickListener noListener){
        VersionUpdataHelper.CustomDialog.Builder builder = new VersionUpdataHelper.CustomDialog.Builder(this);
        builder.setMessage(msg);
        builder.setPositiveButton(ok, okListener);
        builder.setNegativeButton(no, noListener);
        VersionUpdataHelper.CustomDialog dialog  = builder.create();
        dialog.setCancelable(cancelable);
        dialog.show();
    }

    protected boolean checkNet(){
        if (Utils.getNetworkType(this) == 0) {
            showInteractionDialog("网络未开启，是否开启网络", (dialog, which) -> {
                dialog.dismiss();
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            });
            return false;
        }else {
            return true;
        }
    }

    protected void checkGPS(){
        LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gpsIsEnabled){
            showInteractionDialog("需要开启GPS才能正常使用各项功能，是否开启？"
                    ,true
                    ,"开启"
                    ,"不开启"
                    , (dialog, which) -> {
                        dialog.dismiss();
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 0);
                    }, (dialog, which) -> dialog.dismiss());
        }
    }

    protected boolean checkPermission(String... permissions){
        if (permissions.length == 0){
            return EasyPermissions.hasPermissions(this, Constant.sPermissionsArray);
        }else {
            return EasyPermissions.hasPermissions(this, permissions);
        }
    }

    protected void requestPermission(String... permissions){
        if (permissions.length == 0){
            EasyPermissions.requestPermissions(this,
                    getString(R.string.permission_rationale),
                    Constant.REQUEST_PERMISSION_CODE,
                    Constant.sPermissionsArray);
        }else {
            EasyPermissions.requestPermissions(this,
                    getString(R.string.permission_rationale),
                    Constant.REQUEST_PERMISSION_CODE,
                    permissions);
        }
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    protected void initLocation(AMapLocationListener listener){
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        if (listener == null){
            locationClient.setLocationListener(locationListener);
        }else {
            locationClient.setLocationListener(listener);
        }
        startLocation();
    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setGpsFirst(true);
        //可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setHttpTimeOut(30000);
        //可选，设置定位间隔。默认为2秒
        mOption.setInterval(3000);
        //可选，设置是否返回逆地理地址信息。默认是true
        mOption.setNeedAddress(true);
        //可选，设置是否单次定位。默认是false
        mOption.setOnceLocation(false);
        //可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        mOption.setOnceLocationLatest(false);
        //可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTPS);
        //可选，设置是否使用传感器。默认是false
        mOption.setSensorEnable(false);
        //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setWifiScan(true);
        //可选，设置是否使用缓存定位，默认为true
        mOption.setLocationCacheEnable(true);
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = location -> {
        if (null != location) {
            if (location.getLongitude() > 1){
                CommandHelperApplication.setMapLocation(location);
                stopLocation();
                EventBusHelper.sendEventBusMsg(EventBusHelper.LOCATION_SUCCESS);
                Lg.i(TAG, "定位服务运行成功并拿到了数据---loc=== " + location.getAddress());
            }else {
                Lg.i(TAG, "定位服务运行成功，数据异常---loc为0=== " + location.toString());
            }
        } else {
            Lg.i(TAG, "定位服务启动失败---loc is null===");
        }
    };

    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    protected void startLocation(){
        Lg.i(TAG, "---startLocation===");
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    protected void stopLocation(){
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void destroyLocation(){
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
}
